﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ESRI.ArcGIS.Geodatabase;
using EAGL.Data;
using System.Runtime.InteropServices;

namespace EAGL.Data
{
    public class TableLoader
    {
        private ITable table;
        Dictionary<short, short> fmap;


        private void optimizeMapper()
        {
            IFields fields = table.Fields;
            short i = 0;
            while (i < fields.FieldCount)
            {
                if (!fields.get_Field(i).Editable)
                    fmap.Remove(i);
                i++;
            }
        }
        
        private void loadData(ITable src)
        {
            fmap = FieldMapper.GetMappings(table.Fields, src.Fields);
            optimizeMapper();
            IRow row = null;
            ICursor crsr = src.Search(null, true);
            while ((row = crsr.NextRow()) != null)
            {
                IRow r = table.CreateRow();
                foreach (short i in fmap.Keys)
                {
                    r.set_Value(i, row.get_Value(fmap[i]));
                }
                r.Store();
            }
            Marshal.ReleaseComObject(crsr);
        }
        
        public TableLoader(ITable table)
        {
            this.table = table;
        }

        public void Load(ITable src)
        {
            loadData(src);
        }
    }
}
